package com.rocsea.robot.utils;

import com.rocsea.robot.exception.BusinessException;
import com.rocsea.robot.model.bo.EtlExcelColumn;
import com.rocsea.robot.model.bo.EtlExcelSheet;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author RocSea
 * @Date 2023/5/15
 */
public final class EtlStandardUtils {
    private EtlStandardUtils() {
    }

    public static String getCreateTableSqlByExcel(String sourceCreateTableSql, EtlExcelSheet etlExcelSheet) {
        if (StringUtils.isEmpty(sourceCreateTableSql)) {
            throw new BusinessException("源建表语句为空");
        }
        final String splitSymbol = "',";
        StringBuilder sql = new StringBuilder();
        String[] segments = sourceCreateTableSql.split(splitSymbol);
        Map<String, EtlExcelColumn> etlExcelColumnMap = etlExcelSheet.getEtlExcelColumnList().stream().collect(Collectors.toMap(EtlExcelColumn::getSourceColumnEnName,
                Function.identity(), (x1, x2) -> x2));
        String pkColumnName = processTableHead(segments[0], sql, etlExcelColumnMap);
        Map<String, String> usefulFieldMap = new HashMap<>();
        for (int index = 1; index < segments.length; index++) {
            String segment = segments[index];
            int columnStartIndex = segment.indexOf("`");
            int columnEndIndex = segment.lastIndexOf("`");
            String columnName = segment.substring(columnStartIndex + 1, columnEndIndex);
            EtlExcelColumn etlExcelColumn = etlExcelColumnMap.get(columnName);
            if (Objects.isNull(etlExcelColumn)) {
                continue;
            }
            if (!ExcelSemanticsUtils.of(etlExcelColumn.getHasReserve()).isReserve()) {
                continue;
            }
            if (ExcelSemanticsUtils.of(etlExcelColumn.getSuggestedEnName()).notRequiredParse()) {
                if ("update_time".equals(etlExcelColumn.getSuggestedEnName())) {
                    usefulFieldMap.put("update_time", etlExcelColumn.getSourceColumnEnName());
                }
                continue;
            }
            boolean hasLogicDelete = ExcelSemanticsUtils.of(etlExcelColumn.getSuggestedEnName()).hasLogicDelete();
            etlExcelSheet.setHasLogicDel(hasLogicDelete);
            if (hasLogicDelete) {
                usefulFieldMap.put("deleted", etlExcelColumn.getSourceColumnEnName());
                continue;
            }
            segment = segment.replace(etlExcelColumn.getSourceColumnEnName(), etlExcelColumn.getSuggestedEnName());
            segment = segment.replace(etlExcelColumn.getSourceColumnChName(), etlExcelColumn.getSuggestedChName());
            segment = segment.replace(etlExcelColumn.getSourceDataType(), etlExcelColumn.getSuggestedDataType());
            if (!segment.contains("NOT NULL") && !segment.contains("DEFAULT NULL")) {
                segment = "`" + etlExcelColumn.getSuggestedEnName() + "` " + etlExcelColumn.getSuggestedDataType() + " DEFAULT NULL" + " COMMENT " +
                        "'" + etlExcelColumn.getSuggestedChName();
            }
            if (segment.contains("PRIMARY KEY")) {
                break;
            }
            sql.append(segment).append(splitSymbol);
        }
        etlExcelSheet.setUsefulFieldMap(usefulFieldMap);
        if (etlExcelSheet.getHasLogicDel()) {
            sql.append("\n").append("  `deleted` tinyint(4) unsigned DEFAULT NULL COMMENT '是否删除',");
        } else {
            sql.append("\n").append("  `deleted` tinyint(4) unsigned DEFAULT '0' COMMENT '是否删除',");
        }
        sql.append("\n").append("  `update_time_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间id',");
        sql.append("\n").append("  `create_time` datetime DEFAULT NULL COMMENT '创建时间',");
        sql.append("\n").append("  `update_time` datetime DEFAULT NULL COMMENT '更新时间',");
        sql.append("\n").append("  PRIMARY KEY (`").append(pkColumnName).append("`) USING BTREE,");
        sql.append("\n").append("  KEY `idx_update_time_id` (`update_time_id`)");
        sql.append("\n").append(") ENGINE=InnoDB COMMENT='").append(etlExcelSheet.getSourceTableDesc() + "';");
        return sql.toString();
    }

    private static String processTableHead(String tableHead, StringBuilder sql, Map<String, EtlExcelColumn> etlExcelColumnMap) {
        String headSegment = tableHead.split("\n")[1];
        int headSegmentStartIndex = headSegment.indexOf("`");
        int headSegmentEndIndex = headSegment.lastIndexOf("`");
        String columnName = headSegment.substring(headSegmentStartIndex + 1, headSegmentEndIndex);
        tableHead = tableHead.replace("TABLE ", "TABLE `bond_ext_etl`.");
        tableHead = tableHead.replace("AUTO_INCREMENT ", "");
        EtlExcelColumn etlExcelColumn = etlExcelColumnMap.get(columnName);
        tableHead = tableHead.replace(etlExcelColumn.getSourceColumnEnName(), etlExcelColumn.getSuggestedEnName());
        tableHead = tableHead.replace(etlExcelColumn.getSourceDataType(), etlExcelColumn.getSuggestedDataType());
        tableHead = tableHead.replace(etlExcelColumn.getSourceColumnChName(), etlExcelColumn.getSuggestedChName());
        sql.append(tableHead).append("',");
        return columnName;
    }

}
